package com.zenkeeuk.bookerfornfc.client.android;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import org.ksoap2.serialization.SoapObject;

import com.zenkeeuk.bookerfornfc.client.android.book.LabBookHistoryInfo;
import com.zenkeeuk.bookerfornfc.client.android.book.LabBookInfo;
import com.zenkeeuk.bookerfornfc.client.android.book.LabBookListAdapter;
import com.zenkeeuk.bookerfornfc.client.android.book.LabbookHistoryAdapter;
import com.zenkeeuk.bookerfornfc.client.android.history.HistoryManager;
import com.zenkeeuk.bookerfornfc.client.android.http.HttpUtil;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class LabBookDetailActivity extends Activity {

	private ProgressDialog myDialog = null;
	private String message;
	private Contents.GET_LAB_BOOK_HISTORY_MSG getHistoryStatus = Contents.GET_LAB_BOOK_HISTORY_MSG.ERROR;
	
	private String LAB_BOOK_BookName = null;
	private String LAB_BOOK_BookUID = null;
	private String LAB_BOOK_ISBN = null;
	private String LAB_BOOK_remark = null;
	private String LAB_BOOK_time = null;
	private String LAB_BOOK_LibraryName = null;
	private String LAB_BOOK_Location = null;
	private String LAB_BOOK_ToReturnTime = null;
	
	List<LabBookHistoryInfo> listResilt;
	
	@Override
	public void onCreate(Bundle icicle) {
	    super.onCreate(icicle);
	    requestWindowFeature(Window.FEATURE_NO_TITLE);
	    setContentView(R.layout.labbookdetail);
	    
	    myDialog = ProgressDialog.show(this, 
	    		getResources().getString(R.string.progress_labbook_borrow_title),
	    		getResources().getString(R.string.progress_labbook_borrow_notice), true);
		
	    //labBook 
	    LAB_BOOK_BookName = this.getIntent().getStringExtra(Contents.INTENT_EXTRA_LABBOOK_BookName_KEY);
	    LAB_BOOK_BookUID = this.getIntent().getStringExtra(Contents.INTENT_EXTRA_LABBOOK_BookUID_KEY);
	    LAB_BOOK_ISBN = this.getIntent().getStringExtra(Contents.INTENT_EXTRA_LABBOOK_ISBN_KEY);
	    LAB_BOOK_remark = this.getIntent().getStringExtra(Contents.INTENT_EXTRA_LABBOOK_remark_KEY);
	    LAB_BOOK_time = this.getIntent().getStringExtra(Contents.INTENT_EXTRA_LABBOOK_time_KEY);
	    LAB_BOOK_LibraryName = this.getIntent().getStringExtra(Contents.INTENT_EXTRA_LABBOOK_LibraryName_KEY);
	    LAB_BOOK_Location = this.getIntent().getStringExtra(Contents.INTENT_EXTRA_LABBOOK_Location_KEY);
	    LAB_BOOK_ToReturnTime = this.getIntent().getStringExtra(Contents.INTENT_EXTRA_LABBOOK_ToReturnTime_KEY);
	    
	    final ImageButton btn_addfocus = (ImageButton)findViewById(R.id.btn_addfocus);
	    final ImageButton btn_unfocus = (ImageButton)findViewById(R.id.btn_unfocus);
	    
	    boolean isfocused = HistoryManager.getBookIsFocus(LAB_BOOK_BookUID, getBaseContext());
	    if (isfocused) {
	    	btn_addfocus.setVisibility(8);
	    	btn_unfocus.setVisibility(0);
	    } else {
	    	btn_addfocus.setVisibility(0);
	    	btn_unfocus.setVisibility(8);
	    }
	    
	    btn_addfocus.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
            	String tip = "";
            	if (HistoryManager.updateBookFocus(LAB_BOOK_BookUID, LAB_BOOK_ISBN, true, getBaseContext())){
            		tip = "关注当前图书还书信息成功！";
        	    	btn_addfocus.setVisibility(8);
        	    	btn_unfocus.setVisibility(0);
            		
            	} else {
            		tip = "关注当前图书还书信息失败！";
            	}
            	
            	Toast.makeText(getApplicationContext(), 
            			tip,
						Toast.LENGTH_SHORT).show();
            }
	    });
	    
	    btn_unfocus.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
            	String tip = "";
            	if (HistoryManager.updateBookFocus(LAB_BOOK_BookUID, LAB_BOOK_ISBN, false, getBaseContext())){
            		tip = "取消关注当前图书还书信息成功！";
        	    	btn_addfocus.setVisibility(0);
        	    	btn_unfocus.setVisibility(8);
            	} else {
            		tip = "取消关注当前图书还书信息失败！";
            	}
            	
            	Toast.makeText(getApplicationContext(), 
            			tip,
						Toast.LENGTH_SHORT).show();
            }
	    });
	    
	    if (LAB_BOOK_BookUID != null || LAB_BOOK_BookUID.trim().equals("")){
	    	new Thread(getSearchResult).start();
	    } else {
	    	myDialog.dismiss();
	    	Toast.makeText(getApplicationContext(), 
	    			getResources().getString(R.string.progress_labbook_borrow_failed),
	    			Toast.LENGTH_SHORT).show();
	    	this.finish();
	    }
	}
	
	@Override
 	public boolean onCreateOptionsMenu(Menu menu) {
	    super.onCreateOptionsMenu(menu);
	    menu.add(0, Contents.HOME_ID, 0, R.string.menu_home)
	        .setIcon(R.drawable.homebtn);
	    menu.add(0, Contents.HISTORY_ID, 0, R.string.menu_history)
	        .setIcon(R.drawable.historybtn);
	    menu.add(0, Contents.SETTINGS_ID, 0, R.string.menu_settings)
	        .setIcon(R.drawable.settingbtn);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case Contents.HOME_ID: {
	        	Intent intent = new Intent(Intent.ACTION_VIEW);
		        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
		        intent.setClassName(this, HomePageActivity.class.getName());
		        startActivity(intent);
		        break;
	        }
	        case Contents.HISTORY_ID: {
		    	Intent intent = new Intent(Intent.ACTION_VIEW);
			    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
			    intent.setClassName(this, HomePageActivity.class.getName());
			    intent.putExtra(Contents.INTENT_EXTRA_RETURN_TO_TAP_KEY, 1);
			    startActivity(intent);
			    break;
		    }
	        case Contents.SETTINGS_ID: {
	        	Intent intent = new Intent(Intent.ACTION_VIEW);
			    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
			    intent.setClassName(this, HomePageActivity.class.getName());
			    intent.putExtra(Contents.INTENT_EXTRA_RETURN_TO_TAP_KEY, 2);
			    startActivity(intent);
			    break;
	        }
	    }
	    return super.onOptionsItemSelected(item);
	}
	
	public Runnable getSearchResult = new Runnable() {
		public void run() {
			if(LAB_BOOK_BookUID!=null){
				
				try {
					String[] properties = { "bookUID" };
					String[] data = {LAB_BOOK_BookUID};
					
					SoapObject result;
					
					// 取图书馆书信息
				    if (LAB_BOOK_BookName == null) {
				    	result = HttpUtil.getWebServiceData("http://www.zenkee.com/", 
				    			Contents.LAB_SERVICE_HOST_ADDRESS, 
								"GetLabBookByUID",
								"http://www.zenkee.com/GetLabBookByUID",
								properties, data,
								"GetLabBookByUIDResult");
				    	
				    	LAB_BOOK_BookName = result.getPropertyAsString("BookName");
				    	LAB_BOOK_ISBN = result.getPropertyAsString("icbc");
					    LAB_BOOK_remark = result.getPropertyAsString("remark");
					    LAB_BOOK_time = result.getPropertyAsString("time");
					    LAB_BOOK_LibraryName = result.getPropertyAsString("LibraryName");
					    LAB_BOOK_Location = result.getPropertyAsString("Location");
					    LAB_BOOK_ToReturnTime = result.getPropertyAsString("ToReturnTime");
				    }
					
				    // 取借阅历史信息
					result = HttpUtil.getWebServiceData("http://www.zenkee.com/", 
							Contents.LAB_SERVICE_HOST_ADDRESS, 
							"GetBookBorrowedHistory",
							"http://www.zenkee.com/GetBookBorrowedHistory",
							properties, data,
							"GetBookBorrowedHistoryResult");
					
					parseLabBookHistoryInfo(result);
					
					getHistoryStatus = Contents.GET_LAB_BOOK_HISTORY_MSG.OK;
					message = getResources().getString(R.string.progress_labsearch_success);
					
				} catch(Exception e) {
					getHistoryStatus = Contents.GET_LAB_BOOK_HISTORY_MSG.ERROR;
					message = getResources().getString(R.string.progress_labsearch_failed);
				}
				
				messageHandler.sendMessage(messageHandler.obtainMessage());
			}
		}
	};
	
	private void parseLabBookHistoryInfo(SoapObject result) {
		listResilt = new ArrayList<LabBookHistoryInfo>();
		LabBookHistoryInfo labBookHistory = new LabBookHistoryInfo();
		
		int iCount = result.getPropertyCount();
		
		for (int i=0;i<iCount;i++) {
			SoapObject soapObjBook = (SoapObject)result.getProperty(i);
			labBookHistory = new LabBookHistoryInfo();
			labBookHistory.setreaderName(soapObjBook.getPropertyAsString("ReaderName"));
			labBookHistory.setBookuid(soapObjBook.getPropertyAsString("BookUID"));
			labBookHistory.setreadercardUID(soapObjBook.getPropertyAsString("CardUID"));
			labBookHistory.setborrowDate(soapObjBook.getPropertyAsString("BorrowDate"));
			
			String returnDate = soapObjBook.getPropertyAsString("ReturnDate");
			if (returnDate == null || returnDate.isEmpty()||returnDate.equals("anyType{}")) {
				returnDate = "未归还";
			}
			
			labBookHistory.setreturnDate(returnDate);
			
			listResilt.add(labBookHistory);
		}
	}
	
	private void setViews() {
		TextView labbook_detail_name = (TextView)findViewById(R.id.labbook_detail_name);
		TextView labbook_detail_remark = (TextView)findViewById(R.id.labbook_detail_remark);
		TextView labbook_detail_bywho = (TextView)findViewById(R.id.labbook_detail_bywho);
		TextView labbook_detail_libraryname = (TextView)findViewById(R.id.labbook_detail_libraryname);
		TextView labbook_detail_borrow_time = (TextView)findViewById(R.id.labbook_detail_borrow_time);
		TextView labbook_detail_return_time = (TextView)findViewById(R.id.labbook_detail_return_time);
		TextView labbook_detail_borrow_time_lable = (TextView)findViewById(R.id.labbook_detail_borrow_time_lable);
		TextView labbook_detail_return_time_lable = (TextView)findViewById(R.id.labbook_detail_return_time_lable);
		
		labbook_detail_name.setText(LAB_BOOK_BookName);
		labbook_detail_remark.setText(this.LAB_BOOK_remark);
		labbook_detail_libraryname.setText(this.LAB_BOOK_LibraryName);
		
		if(this.LAB_BOOK_remark.equals("已借")) {
			if (listResilt.size()>0) {
				labbook_detail_borrow_time.setVisibility(0);
				labbook_detail_return_time.setVisibility(0);
				labbook_detail_borrow_time_lable.setVisibility(0);
				labbook_detail_return_time_lable.setVisibility(0);
				labbook_detail_bywho.setVisibility(0);
				
				String reader = listResilt.get(0).getreaderName();
				
				labbook_detail_bywho.setText(" by " + reader);
				labbook_detail_borrow_time.setText(this.LAB_BOOK_time);
				labbook_detail_return_time.setText(LAB_BOOK_ToReturnTime);
			}
		} else {
			labbook_detail_borrow_time.setVisibility(8);
			labbook_detail_return_time.setVisibility(8);
			labbook_detail_borrow_time_lable.setVisibility(8);
			labbook_detail_return_time_lable.setVisibility(8);
			labbook_detail_bywho.setVisibility(8);
		}
		
		TextView labbook_borrowed_lable = (TextView)findViewById(R.id.labbook_borrowed_lable);
		MessageFormat message = new MessageFormat(getResources().getString(R.string.labbook_borrow_result_summary));
		labbook_borrowed_lable.setText(message.format(new String[]{String.valueOf(listResilt.size())}));
		
		ListView lv = (ListView)findViewById(R.id.labbook_history_list);
		LabbookHistoryAdapter listAdapter;
		if (listResilt.size() > 0) {
			listAdapter = new LabbookHistoryAdapter(this, listResilt);
		} else {
			listAdapter = null;
		}
		
		lv.setAdapter(listAdapter);
		
		/*
		lv.setOnItemClickListener(new OnItemClickListener(){
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				LabBookHistoryInfo book =  listResilt.get(position);
		  	  	Toast.makeText(getApplicationContext(), book.getBookName(), Toast.LENGTH_SHORT).show();
		  	  	
		  	  	
		        Intent intent = new Intent(getBaseContext(), BookDetailActivity.class);
			    intent.putExtra(Contents.INTENT_EXTRA_ISBN_KEY, book.getBookisbn());
		        startActivity(intent);
		  	  	}
			}
		);*/
	}
	
	
	private Handler messageHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	myDialog.dismiss();
        	Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
            
        	switch(getHistoryStatus){
        		case OK:
        			setViews();
        			break;
        		case ERROR:
        			finish();
        			break;
        	}
        }
	};
	
}
